package cn.edu.cqut.mdm.core.moduleproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

import cn.edu.cqut.mdm.container.InvokableModuleContainer;
import cn.edu.cqut.mdm.core.module.RemoteMethod;
import cn.edu.cqut.mdm.core.module.RemoteModule;
import cn.edu.cqut.mdm.core.module.RemoteModuleEntity;

public class ModuleProxyInterceptor implements InvocationHandler{

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		RemoteModule remoteModuleAnnotaion = method.getDeclaringClass().getAnnotation(RemoteModule.class);
		String uid = remoteModuleAnnotaion.uid();
		List<RemoteModuleEntity> moduleEntities = InvokableModuleContainer.getInstance().getModule(uid);
		for(RemoteModuleEntity moduleEntity : moduleEntities) {
			if(!moduleEntity.isDisabled()) {
				try {
					return moduleEntity.invoke(RemoteMethod.fromMethod(method), args);
				} catch (Exception e) {
					continue;
				}
			}
		}
		return null ;
	}

}
